package cc.rengu.igas.channel.cups.biz.impl;

import cc.rengu.igas.channel.cups.facade.base.BaseRequest;
import cc.rengu.igas.channel.cups.facade.base.BaseResponse;
import cc.rengu.igas.channel.cups.facade.result.Result;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.DubboResult;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.utility.base.StringUtil;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;

/**
 * 通讯模板类
 *
 * @author fangmingwei
 * @date 2020/11/26/16:09
 */
@SuppressWarnings({"unchecked", "rawtypes", "AlibabaClassNamingShouldBeCamel"})
public class CupsCommImplTP<Q extends BaseRequest, P extends BaseResponse> {

    public Result<P> go(Q request, String radpServiceName, Class<P> pclazz) throws Exception {
        RgLogger rglog = RgLog.getLogger(CupsCommImplTP.class.getName());
        DubboService dubboService = new DubboServiceImpl();
        Result<P> result = new Result<>();
        P resp = pclazz.newInstance();
        try {
            DubboResult<P> dubboResult = dubboService.callAtomService(request,
                    radpServiceName, pclazz);
            result.setSuccess(dubboResult.isSuccess());
            if (dubboResult.isSuccess()) {
                result.setResult(dubboResult.getResult());
            } else {
                rglog.error("{}服务调用失败:code<{}>,msg<{}>", radpServiceName, dubboResult.getRespCode(), dubboResult.getRespDesc());
                resp.setRespCode(dubboResult.getRespCode());
                resp.setRespDesc(dubboResult.getRespDesc());
                result.setResult(resp);
            }
        } catch (Exception e) {
            rglog.error("{}服务调用失败:<{}>", radpServiceName, StringUtil.ExceptionToString(e));
            result.setSuccess(false);
            if (e instanceof BizException) {
                resp.setRespCode(((BizException) e).getCode());
                resp.setRespDesc(e.getMessage());
            } else {
                resp.setRespCode(OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
                resp.setRespDesc(OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
            }
            result.setResult(resp);
        }
        return result;
    }
}
